package com.sun.androidexerciseproject.function.api;

import com.sun.androidexerciseproject.function.callback.ResultCallback;
import com.sun.androidexerciseproject.function.model.RequestParam;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/12/6 0006.
 */

public class BaseAPI {
    private OkHttpClient mOkHttpClient;
    private Call mCall;

    private BaseAPI() {
        mOkHttpClient = new OkHttpClient.Builder().connectTimeout(30L, TimeUnit.SECONDS).readTimeout(30L, TimeUnit.SECONDS).build();
    }

    public static BaseAPI getInstance() {
        return Holder.sInstance;
    }

    public void get(String apiUrl, final ResultCallback resultCallback) {
        mCall = mOkHttpClient.newCall(new Request.Builder().url(apiUrl).build());
        doCall(mCall, resultCallback);
    }

    public void post(String apiUrl, RequestParam requestParam, final ResultCallback resultCallback) {
        mCall = mOkHttpClient.newCall(new Request.Builder().url(apiUrl).post(requestParam.getRequestBody()).build());
        doCall(mCall, resultCallback);
    }

    private void doCall(Call call, final ResultCallback resultCallback) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                resultCallback.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                resultCallback.onSuccess(call, response);
            }
        });

    }

    private static final class Holder {
        private static final BaseAPI sInstance = new BaseAPI();
    }
}
